package com.svconnect.plugin.builders;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.svconnect.plugin.model.wsdl.Service;
import com.svconnect.plugin.util.Log;
import com.svconnect.plugin.util.StringUtil;

public class WebConfigBuilder extends BuilderBase {

	public static final String CONFIG_FILENAME = "Web.config";
	
	private static final String EMPTY_CONFIG = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
											"<configuration>" +
											"	<system.serviceModel>" +
											"		<client/>" +
											"	</system.serviceModel>" +
											"</configuration>";
	private String packageName;
	
	public WebConfigBuilder(String referenceDir, String packageName) {
		super();
		this.setReferenceDir(referenceDir);
		this.setPackageName(packageName);
	}
	
	public String getPackageName() {
		return packageName;
	}

	public void setPackageName(String packageName) {
		this.packageName = packageName;
	}
	
	public boolean build(List<Service> services) {

		Log.i("Creating configuration file.");
		try {
			DocumentBuilderFactory domFactory = DocumentBuilderFactory
					.newInstance();
			domFactory.setNamespaceAware(true);
			DocumentBuilder builder = domFactory.newDocumentBuilder();
			
			File file = new File(getConfigFilePath());
			if (file.exists()) {
				file.delete();
			}
			
			InputSource is = new InputSource(new StringReader(EMPTY_CONFIG));
			Document doc = builder.parse(is);
			NodeList nodes = doc.getElementsByTagName("client");
			Element clientNode = (Element)nodes.item(0);
			
			for(Service svc : services) {
				if (svc.getEndpoint()!=null) {
					Element endpointNode = (Element)doc.createElement("endpoint");
					endpointNode.setAttribute("address", svc.getEndpoint().getAddress());
					endpointNode.setAttribute("binding", svc.getEndpoint().getBinding());
					endpointNode.setAttribute("name", svc.getEndpoint().getName());
					
					String contract = String.format("%s.%s%s", packageName, ServiceClientBuilder.INTERFACE_PREFIX, svc.getName());
					endpointNode.setAttribute("contract", contract);
					clientNode.appendChild(endpointNode);
				}
			}
			this.save(doc, getConfigFilePath());
			return true;
		}
		catch(Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}
	
	public String getConfigFilePath() {
		return this.getReferenceDir()+"/../"+CONFIG_FILENAME;
	}
	
	private void save(Document doc, String path) throws TransformerFactoryConfigurationError, TransformerException, IOException {
		String xmlString = StringUtil.toXmlString(doc);
		FileWriter fw = new FileWriter(path);
		fw.write(xmlString);
	}
	
}
